package hdp.http;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jack.netty.log.LoggerManager;
import com.jack.util.string.StringUtil;
import com.richapp.launcher.utils.Tools;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * Created by jack on 16/1/13.
 */
public class HdpKit {

    private static HdpKit hdpKit;
    private Hdiy hdiy;
    private Context context;
    private int changeNum = 1;

    //频道号-频道名
    private Map<Integer,String> channelMap = new HashMap<Integer,String>();

    //频道原名关键字-频道别名
    private Map<String,String[]> aliasMap = new Hashtable<String, String[]>();

    private ServiceConnection connection;

    private HdpKit(){

    }

    private void initAlias(){
        aliasMap.put("CCTV1",new String[]{"中央1套","中央一套","中央1台","中央一台","综合频道"});
        aliasMap.put("CCTV2",new String[]{"中央2套","中央二套","中央2台","中央二台","经济频道"});
        aliasMap.put("CCTV3",new String[]{"中央3套","中央三套","中央3台","中央三台","综艺频道"});
        aliasMap.put("CCTV4",new String[]{"中央4套","中央四套","中央4台","中央四台","国际频道"});
        aliasMap.put("CCTV5",new String[]{"中央5套","中央五套","中央5台","中央五台","体育频道"});
        aliasMap.put("CCTV6",new String[]{"中央6套","中央六套","中央6台","中央六台","电影频道"});
        aliasMap.put("CCTV7",new String[]{"中央7套","中央七套","中央7台","中央七台","军事农业频道"});
        aliasMap.put("CCTV8",new String[]{"中央8套","中央八套","中央8台","中央八台","电视剧频道"});
        aliasMap.put("CCTV9",new String[]{"中央9套","中央九套","中央9台","中央九台","英文国际频道"});
        aliasMap.put("CCTV10",new String[]{"中央10套","中央十套","中央10台","中央十台","科教频道"});
        aliasMap.put("CCTV11",new String[]{"中央11套","中央十一套","中央11台","中央十一台","戏曲频道"});
        aliasMap.put("CCTV12",new String[]{"中央12套","中央十二套","中央12台","中央十二台","普法频道"});
        aliasMap.put("CCTV13",new String[]{"中央13套","中央十三套","中央13台","中央十三台","新闻频道"});
        aliasMap.put("CCTV14",new String[]{"中央14套","中央十四套","中央14台","中央十四台","中央少儿"});
        aliasMap.put("CCTV15",new String[]{"中央15套","中央十五套","中央15台","中央十五台","中央音乐"});
        aliasMap.put("湖南卫视",new String[]{"芒果台","芒果"});
        aliasMap.put("东方卫视",new String[]{"番茄台","番茄"});
        aliasMap.put("江苏卫视",new String[]{"荔枝台","荔枝"});
        aliasMap.put("安徽卫视",new String[]{"皖视","海豚台","海豚"});
        aliasMap.put("四川卫视",new String[]{"熊猫台","熊猫"});
        aliasMap.put("河南卫视",new String[]{"大象台","大象"});
    }

    public static HdpKit getinstance(){
        if(hdpKit == null){
            synchronized (HdpKit.class){
                if(hdpKit == null){
                    hdpKit = new HdpKit();
                }
            }
        }
        return hdpKit;
    }

    public void bindHdpService(Context context){
        this.context = context;
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                hdiy = Hdiy.Stub.asInterface(iBinder);
                getChannels();
                initAlias();
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
        context.bindService(new Intent("hdpfans.com.aidl.Hdiy"), connection, Context.BIND_AUTO_CREATE);
    }

    public void unbindHdpService(){
        if(connection != null && context != null){
            context.unbindService(connection);
        }

        channelMap.clear();
        aliasMap.clear();
    }

    private String getChannels(){
        String result = null;
        try {
            if(hdiy != null){
                result = hdiy.getAllChannelInfo();
                Log.i(getClass().getName(), "channel result:" + result);
            }

            if(!StringUtil.isNullOrEmpty(result)){
                JSONArray channelArr = JSONArray.parseArray(result);
                if(channelArr != null){
                    for(int i = 0 ; i < channelArr.size() ; i++){
                        JSONObject channelObj = channelArr.getJSONObject(i);
                        if(channelObj != null){
                            if(channelObj.containsKey("channelNum") && channelObj.containsKey("channelName")){
                                int channelNum = channelObj.getInteger("channelNum");
                                String channelName = channelObj.getString("channelName");

                                if(!StringUtil.isNullOrEmpty(channelName.trim())){
                                    channelName = channelName
                                            .trim()
                                            .toUpperCase()
                                            .replaceAll(" ","")
                                            .replaceAll("·","")
                                            .replaceAll("\\+","")
                                            .replaceAll("（","")
                                            .replaceAll("）","")
                                            .replaceAll("\\(","")
                                            .replaceAll("\\)","")
                                            .replaceAll("《","")
                                            .replaceAll("》","");
                                    channelMap.put(channelNum,channelName);
                                }
                            }
                        }
                    }
                }
            }

        }catch (Exception e){
            Log.e(getClass().getName(),e == null ? "error:null" : e.getMessage());
        }
        return result;
    }

    public void startApp(int channelNum){
        try {
            Intent intent = new Intent();
            intent.setClassName("hdpfans.com", "hdp.player.StartActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if(channelNum == -1){
                intent.putExtra("ChannelNum", this.changeNum);
            }else{
                intent.putExtra("ChannelNum", channelNum);
                this.changeNum = channelNum;
            }

            context.startActivity(intent);
        }catch (Exception e){
            Log.e(getClass().getName(),e == null ? "startApp error:null" : e.getMessage());
        }

    }

    public void changeChannel(int channelNum){
        try {
            if(Tools.isAPKRun(context,"hdpfans.com")){
                Intent intent = new Intent();
                intent.setClassName("hdpfans.com","hdp.player.LivePlayerNew");
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("ChannelNum", channelNum);
                this.changeNum = channelNum;
                context.startActivity(intent);
                LoggerManager.getInstance().getiLogger().info(getClass(), "改变频道,频道:" + this.changeNum);
            }else{
                startApp(channelNum);
            }
        }catch (Exception e){
            Log.e(getClass().getName(),e == null ? "changeChannel error:null" : e.getMessage());
        }

    }

    public void addChannel(){
        this.changeNum++;
        changeChannel(this.changeNum);
    }

    public void minusChannel(){
        if(this.changeNum > 1){
            this.changeNum--;
            changeChannel(this.changeNum);
        }
    }

    public Map<Integer, String> getChannelMap() {
        return channelMap;
    }

    public Integer getChannelNum(String channelName){
        if(!StringUtil.isNullOrEmpty(channelName.trim())){
            channelName = channelName
                    .trim()
                    .toUpperCase()
                    .replaceAll(" ","")
                    .replaceAll("·","")
                    .replaceAll("\\+","")
                    .replaceAll("（","")
                    .replaceAll("）","")
                    .replaceAll("\\(","")
                    .replaceAll("\\)","")
                    .replaceAll("《","")
                    .replaceAll("》","");

            //如果没有完全相等的，这找个匹配率最高的
            double temp = 0.0;
            String name;
            String tempName;

            int simKey = this.changeNum;
            for(Integer key : channelMap.keySet()){
                name = channelMap.get(key);

                double sim = StringUtil.similal(channelName, name);
                if(sim > temp){
                    temp = sim;
                    simKey = key;
                }


                for(String aliasKey : aliasMap.keySet()){
                    if(name.contains(aliasKey)){
                        for(String value : aliasMap.get(aliasKey)){
                            tempName = name;
                            tempName = tempName.replace(aliasKey,value);

                            sim = StringUtil.similal(channelName, tempName);
                            if(sim > temp){
                                temp = sim;
                                simKey = key;
                            }
                        }
                    }
                }
            }

            return simKey;
        }else{
            return this.changeNum;
        }
    }
}
